package com.ldc.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.catalina.User;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能说明
 *
 * @auther liudc
 * @since 2023/6/24
 */
public class JwtUtils {
    private static final String APP_SECRET = "!@#!@#";
    private static final Algorithm algorithm = Algorithm.HMAC256(APP_SECRET);
    private final static String USER_ID = "user_id";
    private final static String USER_NAME = "user_name";

    public JwtUtils() {
        throw new IllegalStateException("非法创建");
    }


    public static String createToken(String userId, String userName) {
        Map<String, String> map = new HashMap<>();
        map.put(USER_ID, userId);
        map.put(USER_NAME, userName);
        return createToken(map);
    }

    public static String createToken(Map<String, String> params) {
        try {
            Map<String, Object> header = new HashMap<>();
            header.put("author", "ldc");
            JWTCreator.Builder builder = JWT.create();
            final Date currentDate = DateTimeUtils.getDate();
            final Date expireDate = DateTimeUtils.addHour(currentDate.getTime(), 10);
            builder.withExpiresAt(expireDate)
                    .withIssuedAt(currentDate);
            // header
            builder.withHeader(header);
            // 数据封装
            params.forEach(builder::withClaim);

            return builder.sign(algorithm);
        } catch (JWTCreationException jwtCreationException) {
            return "";
        }
    }


    public static DecodedJWT verifier(DecodedJWT decodedJWT) {
        if (decodedJWT == null) {
            return null;
        }
        return JWT.require(algorithm).build().verify(decodedJWT);
    }

    public static DecodedJWT verifierToken(String token) {
        if (StringUtils.hasLength(token)) {
            return JWT.require(algorithm).build().verify(token);
        }
        return null;
    }


    public static boolean available(String token) {
        return verifierToken(token) != null;
    }

    public static boolean notAvailable(String token) {
        return !available(token);
    }

    public static String getClaim(String token, String key) {
        if (available(token)) {
            return verifierToken(token).getClaim(key).asString();
        }
        return "";
    }


    public static String getUserName(String token) {
        return getClaim(token, USER_NAME);
    }

    public static String getUserId(String token) {
        return getClaim(token, USER_ID);
    }


}
